#!/usr/bin/python
#-*- coding:utf-8 -*-


import sys, time, os,commands, multiprocessing,pxssh,arg

##############################################
#	setting                             #
#############################################
#远程服务器ip及登录用户
addr_map = {
	'server_1' : ('root','192.168.8.211','5044'),
}
#远程服务器上的功能脚本

cmd_map = {
    'ls' : "cd /root/workspace/",
    'huitui':"sh /root/workspace/script_git/huitui.sh ",
    'fabu' : "sh /root/workspace/script_git/fabu.sh ",
    'rm': "rm -rf /root/workspace/"
}

####################################################
#             control (need not to change)
###################################################
if sys.argv[1]=="ls":
    cmd_key = sys.argv[1]
    if len(sys.argv) == 3:  cmd     = cmd_map[cmd_key]+sys.argv[2]+";result=`ls`;echo $result"
    else: cmd=cmd_map[cmd_key]+";result=`ls`;echo $result"
elif sys.argv[1]=="new":
    message=os.popen("sh /usr/local/git/new.sh "+sys.argv[2])
    #cmd = "cd /root/workspace;"+"mkdir "+sys.argv[2]+"; cd "+sys.argv[2]+";git clone  ssh://root@192.168.8.205:5044/usr/local/git/file"+sys.argv[2]+";sh /root/workspace/script_git/fabu.sh "+' master'+' '+sys.argv[2]
    cmd = "cd /root/workspace;"+"git clone  ssh://root@192.168.8.205:5044/usr/local/git/file/"+sys.argv[2]+";cd "+sys.argv[2]+";ls"
elif len(sys.argv) == 2:
    try:
    	cmd_key = sys.argv[1]
    	branch = sys.argv[2]
    	cmd     = cmd_map[cmd_key]+' '+branch
    except:
    	sys.stderr.write("Usage: python %s cmd local_branch:remote_branch project_name\n" % sys.argv[0])
    	print """ 
    			cmd: huitui or fabu 
	      """
    	raise SystemExit(1)
elif len(sys.argv) == 1:
    try:
	cmd_key = sys.argv[1]
	cmd	= cmd_map[cmd_key]
    except:
    	sys.stderr.write("Usage: python %s cmd local_branch:remote_branch project_name\n" % sys.argv[0])
    	print """ 
    			cmd: huitui or fabu 
	      """
        raise SystemExit(1)    

elif len(sys.argv) == 4:
    try:
	cmd_key = sys.argv[1]
	branch  = sys.argv[2]
	project_name	= sys.argv[3]
	cmd     = cmd_map[cmd_key]+' '+branch+' '+project_name
    except:
	sys.stderr.write("Usage: python %s cmd local_branch:remote_branch project_name\n" % sys.argv[0])
	raise SystemExit(1)

class JsshProcess(multiprocessing.Process):
    def __init__(self, server_id):
        multiprocessing.Process.__init__(self)
        self.server_id = server_id
    def run(self):
	server=pxssh.pxssh()
	info=addr_map[self.server_id]
	server.login(info[1],info[0],port=info[2])
	server.sendline('%s ' %cmd)
	server.prompt()
	commands_output=server.before
	print commands_output + self.server_id

for key in addr_map:
	p = JsshProcess(key)
	p.start()
